package com.frame.pageform.job;

import java.util.ArrayList;
import java.util.List;


/**
 * 任务调度室
 * @author Administrator
 *
 */
public class Schedule {
	private Pool pool;
	private int interval=-1;

	private boolean started=false;
	/**
	 * 主线程
	 */
	private Thread thread = new Thread()
	{
		public void run()
		{
			while(true)
			{
				Schedule.this.run();
			}
		}
	};
	public Schedule(){
		//初始化线程池
		pool=ThreadPoolFactory.createThreadPool(3);
	}
	/**
	 * 任务列表
	 */
	private List jobs=new ArrayList();

	public void start(){
		//启动调度室
		thread.start();
		System.out.println("开始启动任务调度..");
	}
	synchronized private void run(){
		long time = System.currentTimeMillis();
		int n=jobs.size();
		for(int i=0;i<n;i++){
			Job job=(Job)jobs.get(i);
			if(job.getInterval()<interval || interval<0)
				interval=job.getInterval();
			long jobtime=job.getLastTime();
			long l=jobtime+(job.getInterval()*1000);
			if(time>l){
				try {
					pool.execute(job);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//这里允许错误
				}
			}
		}
		started=true;
		try {
			if(interval>0)
				wait(interval*1000);
			else
				wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public void addJob(Job job){
		synchronized(this){
			jobs.add(job);
			if(started)
				notify();
		}
	}

}
